MESSAGE( STATUS ">> -------------------------------------------------------------------- <<" )
MESSAGE( STATUS ">> --------------------- UI - CPP ------------------------------------- <<" )

######### CMake Version #####################
cmake_minimum_required( VERSION 3.0 )
#############################################



######### Project Name ######################
project( Spirit_UI_CPP )
#############################################



### Find includes in corresponding build directories
set( CMAKE_INCLUDE_CURRENT_DIR ON )
### Let CMake run moc on QT ui files automatically
set( CMAKE_AUTOMOC ON )
### Let CMake collect QT Resources automatically
set( CMAKE_AUTORCC ON )
### Let CMake handle .ui files automatically
# set(CMAKE_AUTOUIC ON) # unfortunately, for this, .ui files ned to be next to corresponding .cpp files
######### Have the binary placed into the source head
### Output paths for single-config builds
# set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR})
# set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin)
# set(PROJECT_BINARY_DIR ${CMAKE_SOURCE_DIR}/bin2)
# set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib)
# set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/lib)
set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR} )
### Output paths for multi-config builds (e.g. msvc)
foreach( OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES} )
    string( TOUPPER ${OUTPUTCONFIG} OUTPUTCONFIG )
    set( CMAKE_RUNTIME_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_SOURCE_DIR} )
    # set( CMAKE_LIBRARY_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${youroutputdirectory} )
    # set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${youroutputdirectory} )
endforeach( OUTPUTCONFIG CMAKE_CONFIGURATION_TYPES )
### Apple app bundle path
if ( APPLE AND SPIRIT_BUNDLE_APP )
    set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_INSTALL_PREFIX}/bin )
endif ( )
### Installation
set( CMAKE_INSTALL_PREFIX ${CMAKE_BINARY_DIR} )
#############################################
# set( CMAKE_DISABLE_SOURCE_CHANGES  ON )
set( CMAKE_DISABLE_IN_SOURCE_BUILD ON )
#############################################


add_subdirectory    ( ${PROJECT_SOURCE_DIR}/utility )
include_directories ( ${PROJECT_SOURCE_DIR}/include
                      ${SPIRIT_INCLUDE_DIRS} )

if( SPIRIT_UI_CXX_USE_QT )

    ######### QT Path ########################
    if( USER_PATH_QT )
        set( CMAKE_PREFIX_PATH ${USER_PATH_QT} )
    else()
        ### IFF and developers' default paths
        if ( WIN32 )
            set( CMAKE_PREFIX_PATH "C:/QT/5.7/msvc2015/" )
        elseif ( APPLE)
            set( CMAKE_PREFIX_PATH "/usr/local/qt5/" )
        elseif ( UNIX)
            set( CMAKE_PREFIX_PATH "/usr/local/qt5/" )
        endif()
    endif()
    MESSAGE( STATUS ">> Please check the CMAKE_PREFIX_PATH to make sure QT5 is found")
    MESSAGE( STATUS ">> CMAKE_PREFIX_PATH:             " ${CMAKE_PREFIX_PATH} )
    ##########################################



    ######### Find the Qt libraries ##########
    find_package( Qt5 5.7 REQUIRED COMPONENTS Core Gui Widgets Charts OpenGL )
    MESSAGE( STATUS ">> QT version:  " ${Qt5_VERSION} )
    MESSAGE( STATUS ">> Found QT at: " ${Qt5_DIR} )
    ###########################################



    ######### Where to search for library headers
    include_directories(${GLAD_INCLUDE_DIRS}
                        ${GLM_INCLUDE_DIRS}
                        ${GL_INCLUDE_DIRS}
                        ${CMAKE_SOURCE_DIR}/VFRendering/include)
    ###########################


    ######### Subdirectories to look for CMakeLists.txt
    ### Header Gropus
    set( HEADER_UI_QT_ROOT )
    ### Source Groups
    set( SOURCE_UI_QT_ROOT )
    ### Add Subdirectories
    add_subdirectory( ${PROJECT_SOURCE_DIR}/src )
    add_subdirectory( ${PROJECT_SOURCE_DIR}/include )
    add_subdirectory( ${PROJECT_SOURCE_DIR}/ui )
    ### Folder include
    source_group( "include" FILES ${HEADER_UI_QT_ROOT} )
    ### Folder src
    source_group( ""    FILES ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
    source_group( "src" FILES ${SOURCE_UI_QT_ROOT} )
    source_group( "ui"  FILES ${UI_FILES} )
    ###########################

    ######### Convert UI Files to Headers
    qt5_wrap_ui( UI_SOURCE ${UI_FILES} )
    #############################################


    ######### THIS IS VERY UGLY, but makes the VS project tidy... a nicer solution is welcome!
    if( SPIRIT_UI_CXX_USE_QT )
    set( AUTOGENERATED_FILES
        ${PROJECT_BINARY_DIR}/CMakeFiles/${PROJECT_NAME}.dir/qrc_resources.cpp
        ${PROJECT_BINARY_DIR}/qrc_resources_HAS2BXGMQQBHVI.cpp
        ${PROJECT_BINARY_DIR}/${PROJECT_NAME}_automoc.cpp
        ${PROJECT_BINARY_DIR}/ui_DebugWidget.h
        ${PROJECT_BINARY_DIR}/ui_MainWindow.h
        ${PROJECT_BINARY_DIR}/ui_PlotsWidget.h
        ${PROJECT_BINARY_DIR}/ui_SettingsWidget.h
        ${PROJECT_BINARY_DIR}/ui_ControlWidget.h
        ${PROJECT_BINARY_DIR}/ui_IsosurfaceWidget.h
        ${PROJECT_BINARY_DIR}/ui_ParametersWidget.h
        ${PROJECT_BINARY_DIR}/ui_VisualisationSettingsWidget.h)
    source_group( "autogenerated" FILES ${AUTOGENERATED_FILES})
    endif( )
    #############################################



    #############################################
    SET( OS_BUNDLE_NAME )
    SET( META_FILES )
    IF( APPLE AND SPIRIT_BUNDLE_APP )

        # For Apple set the icns file containing icons
        # set how it shows up in the Info.plist file
        SET( MACOSX_BUNDLE_ICON_FILE AppIcon.icns ) 
        # set where in the bundle to put the icns file
        SET_SOURCE_FILES_PROPERTIES( ${CMAKE_CURRENT_SOURCE_DIR}/res/AppIcon.icns PROPERTIES MACOSX_PACKAGE_LOCATION Resources )
        # include the icns file in the target
        SET( SOURCE_UI_QT_ROOT ${SOURCE_UI_QT_ROOT} ${CMAKE_CURRENT_SOURCE_DIR}/QtTest.icns )

        # Setup RPATH so that built executable targets will run in both the
        # build tree and the install location without having to set a
        # (DYLD|LD)_LIBRARY_PATH override.
        #

        # use the full RPATH of the build tree
        set ( CMAKE_SKIP_BUILD_RPATH FALSE )

        # when building, don't use the install RPATH, it will still be used
        # later on in the install phase
        set ( CMAKE_BUILD_WITH_INSTALL_RPATH FALSE )

        # set (CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${WSJT_LIB_DESTINATION}")

        # add the automaticaly determined parts of the RPATH which point to
        # directories outside of the build tree to the install RPATH
        set ( CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE )

        # the RPATH to be used when installing, but only if it's not a system
        # directory
        # list (FIND CMAKE_PLATFORM_IMPLICIT_LINK_DIRECTORIES "${CMAKE_INSTALL_PREFIX}/${WSJT_LIB_DESTINATION}" isSystemDir)
        # if ("${isSystemDir}" STREQUAL "-1")
        #   set (CMAKE_INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/${WSJT_LIB_DESTINATION}")
        # endif ("${isSystemDir}" STREQUAL "-1")

        set( QT_NEED_RPATH FALSE )
            if( NOT "${QT_LIBRARY_DIR}" STREQUAL "/lib" AND NOT "${QT_LIBRARY_DIR}" STREQUAL "/usr/lib" AND NOT "${QT_LIBRARY_DIR}" STREQUAL "/lib64" AND NOT "${QT_LIBRARY_DIR}" STREQUAL "/usr/lib64" )
            set( QT_NEED_RPATH TRUE )
        endif( )
        
        SET( OS_BUNDLE_NAME MACOSX_BUNDLE )
    ENDIF( APPLE AND SPIRIT_BUNDLE_APP )
    ###
    IF( WIN32 AND SPIRIT_BUNDLE_APP )
        SET( OS_BUNDLE_NAME WIN32 )
    ENDIF ( WIN32 AND SPIRIT_BUNDLE_APP )
    ###
    IF( WIN32 )
        set(ICON_FILE ${CMAKE_CURRENT_SOURCE_DIR}/res/AppIcon.ico)
        configure_file(
            ${CMAKE_CURRENT_SOURCE_DIR}/res/windows_metafile.rc.in
            ${CMAKE_CURRENT_SOURCE_DIR}/windows_metafile.rc )
        SET( SOURCE_UI_QT_ROOT ${SOURCE_UI_QT_ROOT} "windows_metafile.rc" )
        set(CMAKE_RC_COMPILER_INIT windres)
        ENABLE_LANGUAGE(RC)
        SET(CMAKE_RC_COMPILE_OBJECT "<CMAKE_RC_COMPILER> <FLAGS> -O coff <DEFINES> -i <SOURCE> -o <OBJECT>")
    ENDIF( )
    #############################################


    #############################################
    # stuff only qmake can tell us
    get_target_property ( QMAKE_EXECUTABLE Qt5::qmake LOCATION )
    function ( QUERY_QMAKE VAR RESULT )
        exec_program ( ${QMAKE_EXECUTABLE} ARGS "-query ${VAR}" RETURN_VALUE return_code OUTPUT_VARIABLE output )
        if ( NOT return_code )
            file ( TO_CMAKE_PATH "${output}" output )
            set ( ${RESULT} ${output} PARENT_SCOPE )
        endif ( NOT return_code )
        message ( STATUS "Asking qmake for ${RESULT} and got ${output}" )
    endfunction ( QUERY_QMAKE )

    query_qmake ( QT_INSTALL_PLUGINS QT_PLUGINS_DIR )
    query_qmake ( QT_INSTALL_IMPORTS QT_IMPORTS_DIR )
    query_qmake ( QT_HOST_DATA QT_DATA_DIR )
    set ( QT_MKSPECS_DIR ${QT_DATA_DIR}/mkspecs )
    #############################################

endif( SPIRIT_UI_CXX_USE_QT )





######### Tell CMake to create the executable
### Set sources
set( ALL_SOURCES main.cpp ${UI_CPP_UTILITY} )

if( SPIRIT_UI_CXX_USE_QT )
    set( ALL_SOURCES ${ALL_SOURCES}
        ${HEADER_UI_QT_ROOT}
        ${SOURCE_UI_QT_ROOT}
        ${UI_SOURCE}
        resources.qrc )
endif( )
### Bundle Var will be empty if bundle should
### not be created
add_executable( ${PROJECT_NAME} ${OS_BUNDLE_NAME} ${ALL_SOURCES} )
### Set executable name
set( SPIRIT_EXE_NAME "spirit" )
set_target_properties( ${PROJECT_NAME} PROPERTIES OUTPUT_NAME ${SPIRIT_EXE_NAME} )
#############################################

target_include_directories( ${PROJECT_NAME} PRIVATE ${PROJECT_BINARY_DIR}/thirdparty-install/include/ )

######### Link the libraries into the executable
target_link_libraries( ${PROJECT_NAME} ${SPIRIT_LIBRARIES_STATIC} )
### QT UI Libraries
if( SPIRIT_UI_CXX_USE_QT )
    set( THREADS_PREFER_PTHREAD_FLAG ON )
    find_package( Threads REQUIRED )
    target_link_libraries( ${PROJECT_NAME} Threads::Threads )
    target_link_libraries( ${PROJECT_NAME} ${GL_LIBRARIES} Qt5::Core Qt5::Gui Qt5::Widgets Qt5::Charts Qt5::OpenGL VFRendering )
endif( )
### OSX and Unix need libdl
if( APPLE OR UNIX )
    target_link_libraries( ${PROJECT_NAME} dl )
endif()
#############################################



######### Generate a .user file for VS to set the VS Working Directory
if ( WIN32 )
	set( USERFILE_PLATFORM "Win32" )
	set( USERFILE_WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} )
	MESSAGE( STATUS ">> Windows Platform:           " ${USERFILE_PLATFORM} )
	MESSAGE( STATUS ">> Windows Working Dir:        " ${USERFILE_WORKING_DIRECTORY} )
	### Output a .user file for VS to use, setting the VS Working Directory
	configure_file( ${CMAKE_SOURCE_DIR}/CMake/working_directory.vcxproj.user.in ${PROJECT_BINARY_DIR}/${PROJECT_NAME}.vcxproj.user @ONLY )
endif()
#############################################



######### General installation stuff ########
#--------------------------------------------------------------------------------
# Now the installation stuff below
#--------------------------------------------------------------------------------
SET( plugin_dest_dir bin )
SET( qtconf_dest_dir bin )
SET( APPS "\${CMAKE_INSTALL_PREFIX}/bin/${SPIRIT_EXE_NAME}" )

IF( APPLE AND SPIRIT_BUNDLE_APP )
    SET(plugin_dest_dir ${PROJECT_NAME}.app/Contents )
    SET(qtconf_dest_dir ${PROJECT_NAME}.app/Contents/Resources )
    SET(APPS "\${CMAKE_INSTALL_PREFIX}/bin/${SPIRIT_EXE_NAME}.app" )
ENDIF( APPLE AND SPIRIT_BUNDLE_APP )

IF( WIN32 )
    SET( APPS "\${CMAKE_INSTALL_PREFIX}/bin/${SPIRIT_EXE_NAME}.exe" )
ENDIF( WIN32 )


#--------------------------------------------------------------------------------
# Install the QtTest application, on Apple, the bundle is at the root of the
# install tree, and on other platforms it'll go into the bin directory.
INSTALL( TARGETS ${PROJECT_NAME} DESTINATION bin )
    # BUNDLE DESTINATION . COMPONENT Runtime
    # RUNTIME DESTINATION bin COMPONENT Runtime )

# install(DIRECTORY docs DESTINATION docs/Spirit/ui-qt)


if( SPIRIT_UI_CXX_USE_QT )

    #--------------------------------------------------------------------------------
    # Install needed Qt plugins by copying directories from the qt installation
    # One can cull what gets copied by using 'REGEX "..." EXCLUDE'
    # set( QT_PLUGINS_DIR "/usr/local/qt-5.7/plugins")
    INSTALL( DIRECTORY
                ${QT_PLUGINS_DIR}/platforms
                ${QT_PLUGINS_DIR}/imageformats
            DESTINATION
                ${plugin_dest_dir}/PlugIns
            COMPONENT
                Runtime
            FILES_MATCHING
                PATTERN "*${CMAKE_SHARED_LIBRARY_SUFFIX}"
                PATTERN "*minimal*${CMAKE_SHARED_LIBRARY_SUFFIX}" EXCLUDE
                PATTERN "*offscreen*${CMAKE_SHARED_LIBRARY_SUFFIX}" EXCLUDE
                PATTERN "*quick*${CMAKE_SHARED_LIBRARY_SUFFIX}" EXCLUDE
                PATTERN "*_debug${CMAKE_SHARED_LIBRARY_SUFFIX}" EXCLUDE )

    #--------------------------------------------------------------------------------
    # install a qt.conf file
    # this inserts some cmake code into the install script to write the file
    INSTALL( CODE "
        file(WRITE \"\${CMAKE_INSTALL_PREFIX}/bin/qt.conf\" \"\")
        " COMPONENT Runtime )


    #--------------------------------------------------------------------------------
    # Use BundleUtilities to get all other dependencies for the application to work.
    # It takes a bundle or executable along with possible plugins and inspects it
    # for dependencies.  If they are not system dependencies, they are copied.

    # directories to look for dependencies
    SET( DIRS ${QT_LIBRARY_DIRS} )

    # Now the work of copying dependencies into the bundle/package
    # The quotes are escaped and variables to use at install time have their $ escaped
    # An alternative is the do a configure_file() on a script and use install(SCRIPT  ...).
    # Note that the image plugins depend on QtSvg and QtXml, and it got those copied
    # over.
    INSTALL( CODE "
        file(GLOB_RECURSE QTPLUGINS
        \"\${CMAKE_BINARY_DIR}/${plugin_dest_dir}/plugins/*${CMAKE_SHARED_LIBRARY_SUFFIX}\")
        include(BundleUtilities)
        fixup_bundle(\"${APPS}\" \"\${QTPLUGINS}\" \"${DIRS}\")
        " COMPONENT Runtime )

endif( SPIRIT_UI_CXX_USE_QT )

#--------------------------------------------------------------------------------
# To Create a package, one can run "cpack -G DragNDrop CPackConfig.cmake" on Mac OS X
# where CPackConfig.cmake is created by including CPack
# And then there's ways to customize this as well
INCLUDE( InstallRequiredSystemLibraries )
set( CPACK_BINARY_DRAGNDROP ON )
include( CPack )


#--------------------------------------------------------------------------------
if( APPLE AND SPIRIT_BUNDLE_APP )
    execute_process( COMMAND chmod +x "${CMAKE_BINARY_DIR}/${SPIRIT_EXE_NAME}.app" )
    execute_process( COMMAND chmod +x "${CMAKE_BINARY_DIR}/${SPIRIT_EXE_NAME}.app/Contents/MacOS/${SPIRIT_EXE_NAME}" )
endif( )
#############################################



######### Header and Source messages ########
if( SPIRIT_PRINT_SOURCES )
    MESSAGE( STATUS ">> Utility:                    ${UI_CPP_UTILITY}" )
    MESSAGE( STATUS ">> Headers:                    ${HEADER_UI_QT_ROOT}" )
    MESSAGE( STATUS ">> Sources:                    ${SOURCE_UI_QT_ROOT}" )
    MESSAGE( STATUS ">> UI Files:                   ${UI_SOURCE}" )
    MESSAGE( STATUS ">> Autogenerated Files:        ${AUTOGENERATED_FILES}" )
endif ()
#############################################

MESSAGE( STATUS ">> --------------------- UI - CPP done -------------------------------- <<" )
MESSAGE( STATUS ">> -------------------------------------------------------------------- <<" )
